﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DAO;

namespace TAM_SPORT
{
    public partial class FSale : TAM_SPORT.FormBase
    {
        private CustomerDao dao;
        private ProductDao pdao;
        private SalesDao sdao;
        public FSale()
        {
            InitializeComponent();
            dao = new CustomerDao();
            loadCbx();
            pdao = new ProductDao();
            cbxCustomer.SelectedIndex = 0;            
            loadProuct();
            sdao = new SalesDao();
            loadGrid();
            cbxProduct.SelectedIndex = 0;
        }

        private void loadGrid()
        {
            DataTable table = sdao.getSales(dtFrom.Value, dtTo.Value);
            double allTotal = 0;
            double debit = 0;
            double realTotal = 0;
            dtgCustomers.Rows.Clear();
            if (table != null && table.Rows.Count > 0)
            {
                foreach (DataRow row1 in table.Rows)
                {
                    allTotal += Convert.ToDouble(row1["TOTAL"]);
                    debit += Convert.ToDouble(row1["DEBIT_MONEY"]);
                    realTotal += Convert.ToDouble(row1["PAY_MONEY"]);
                    int i = dtgCustomers.Rows.Add();
                    dtgCustomers.Rows[i].Cells[0].Value = i + 1;
                    dtgCustomers.Rows[i].Cells[1].Value = row1["CUSTOMER_NAME"].ToString();
                    dtgCustomers.Rows[i].Cells[2].Value = row1["PRODUCT_NAME"].ToString();
                    dtgCustomers.Rows[i].Cells[3].Value = row1["UNIT_NAME"].ToString();
                    dtgCustomers.Rows[i].Cells[4].Value = Convert.ToDouble(row1["SO_LUONG"]).ToString("#,###.##");
                    dtgCustomers.Rows[i].Cells[5].Value = Convert.ToDouble(row1["TOTAL"]).ToString("#,###.##");
                    dtgCustomers.Rows[i].Cells[6].Value = Convert.ToDouble(row1["PAY_MONEY"]).ToString("#,###.##");
                    dtgCustomers.Rows[i].Cells[7].Value = Convert.ToDouble(row1["DEBIT_MONEY"]).ToString("#,###.##");
                    dtgCustomers.Rows[i].Cells[8].Value = row1["ID"].ToString();
                    if (i % 2 == 1)
                    {
                        dtgCustomers.Rows[i].DefaultCellStyle.BackColor = Color.LightCyan;
                    }
                }
            }
            txtAlltotal.Text = allTotal.ToString("#,###.##");
            txtDebit.Text = debit.ToString("#,###.##");
            txtReadTotal.Text = realTotal.ToString("#,###.##");
        }

        private void loadCbx()
        {
            DataTable table = dao.getCustomers();
            cbxCustomer.DataSource = table;
            DataRow row = table.NewRow();
            row["ID"] = -1;
            row["NAME"] = "Không chọn khách";
            table.Rows.InsertAt(row, 0);
            cbxCustomer.DisplayMember = "NAME";
            cbxCustomer.ValueMember = "ID";
        }

        private void loadProuct()
        {
            DataTable table = pdao.getProductsForSale(string.Empty);
            cbxProduct.DataSource = table;
            DataRow row = table.NewRow();
            row["ID"] = -1;
            row["NAME"] = "Chọn sản phầm";
            table.Rows.InsertAt(row, 0);
            cbxProduct.DisplayMember = "NAME";
            cbxProduct.ValueMember = "ID";
        }

        private void cbxProduct_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbxProduct.SelectedIndex >= 1)
            {
                int productId = 0;
                int.TryParse(cbxProduct.SelectedValue.ToString(), out productId);
                if (productId > 0)
                {
                    DataRow row = pdao.getProDuctById(productId);
                    if (row != null)
                    {
                        txtPrice.Text = ((double)row["PRICE"]).ToString("#,###.##");
                        txtUnit.Text = row["UNIT_NAME"].ToString();
                    }
                }
                else
                {
                    txtPrice.Text = "";
                }
            }
            else
            {
                txtPrice.Text = "";
            }

            if (!string.IsNullOrEmpty(txtPayMoney.Text))
            {
                decimal payMoney = Convert.ToDecimal(RemoveComma(txtPayMoney.Text));
                if (!string.IsNullOrEmpty(txtTotal.Text))
                {
                    decimal total = Convert.ToDecimal(txtTotal.Text);
                    decimal debit = total - payMoney;
                    if (debit >= 0)
                    {
                        txtDebitMoney.Text = debit.ToString("#,##0");
                    }
                    else
                    {
                        txtDebitMoney.Text = "(" + (-1 * debit).ToString("#,##0") + ")";
                    }
                }

            }
            else
            {
                txtDebitMoney.Text = txtTotal.Text;
            }
        }

        private String RemoveComma(String value)
        {
            if (value != null && value.Contains(","))
            {
                value = value.Replace(",", String.Empty).Trim();
            }
            return value;
        }


        private void txtPrice_TextChanged(object sender, EventArgs e)
        {
            if (RemoveComma(txtPrice.Text).Length > 3)
            {
                txtPrice.Text = decimal.Parse(RemoveComma(txtPrice.Text)).ToString("#,###");
                txtPrice.Select(txtPrice.Text.Length, 0);
            }
            if(!string.IsNullOrEmpty(txtPrice.Text))
            {
                decimal price = Convert.ToDecimal(RemoveComma(txtPrice.Text));
                decimal quantity = nbquantity.Value;
                if(quantity > 0)
                {
                    txtTotal.Text = (price * quantity).ToString("#,###");
                    txtPayMoney.Text = (price * quantity).ToString("#,###");
                }
                
            }
            if (!string.IsNullOrEmpty(txtPayMoney.Text))
            {
                decimal payMoney = Convert.ToDecimal(RemoveComma(txtPayMoney.Text));
                if (!string.IsNullOrEmpty(txtTotal.Text))
                {
                    decimal total = Convert.ToDecimal(txtTotal.Text);
                    decimal debit = total - payMoney;
                    if (debit >= 0)
                    {
                        txtDebitMoney.Text = debit.ToString("#,##0");
                    }
                    else
                    {
                        txtDebitMoney.Text = "(" + (-1 * debit).ToString("#,##0") + ")";
                    }
                }

            }
            else
            {
                txtDebitMoney.Text = txtTotal.Text;
            }
        }

        private void txtPrice_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar)
            && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void nbquantity_ValueChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtPrice.Text))
            {
                decimal price = Convert.ToDecimal(RemoveComma(txtPrice.Text));
                decimal quantity = nbquantity.Value;
                if (quantity > 0)
                {
                    txtTotal.Text = (price * quantity).ToString("#,###");
                    txtPayMoney.Text = (price * quantity).ToString("#,###");
                }

            }
            if (!string.IsNullOrEmpty(txtPayMoney.Text))
            {
                decimal payMoney = Convert.ToDecimal(RemoveComma(txtPayMoney.Text));
                if (!string.IsNullOrEmpty(txtTotal.Text))
                {
                    decimal total = Convert.ToDecimal(txtTotal.Text);
                    decimal debit = total - payMoney;
                    if (debit >= 0)
                    {
                        txtDebitMoney.Text = debit.ToString("#,##0");
                    }
                    else
                    {
                        txtDebitMoney.Text = "(" + (-1 * debit).ToString("#,##0") + ")";
                    }
                }

            }
            else
            {
                txtDebitMoney.Text = txtTotal.Text;
            }
        }

        private void txtPayMoney_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar)
            && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void txtPayMoney_TextChanged(object sender, EventArgs e)
        {
            if (RemoveComma(txtPayMoney.Text).Length > 3)
            {
                txtPayMoney.Text = decimal.Parse(RemoveComma(txtPayMoney.Text)).ToString("#,###");
                txtPayMoney.Select(txtPayMoney.Text.Length, 0);
            }
            if (!string.IsNullOrEmpty(txtPayMoney.Text))
            {
                decimal payMoney = Convert.ToDecimal(RemoveComma(txtPayMoney.Text));
                if (!string.IsNullOrEmpty(txtTotal.Text))
                {
                    decimal total = Convert.ToDecimal(txtTotal.Text);
                    decimal debit = total - payMoney;
                    if (debit >= 0)
                    {
                        txtDebitMoney.Text = debit.ToString("#,##0");
                    }
                    else
                    {
                        txtDebitMoney.Text = "(" + (-1 * debit).ToString("#,##0") + ")";
                    }
                }

            }
            else
            {
                txtDebitMoney.Text = txtTotal.Text;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            bool errflg = false;
            if (string.IsNullOrEmpty(txtPrice.Text) || nbquantity.Value <= 0)
            {
                Error f = new Error("Vui lòng nhập đầy đủ thông tin");
                f.ShowDialog();
                f.Dispose();
                errflg = true;
            }
            if (cbxProduct.SelectedIndex <= 0)
            {
                Error f = new Error("Chưa chọn sản phẩm để bán");
                f.ShowDialog();
                f.Dispose();
                errflg = true;
            }
            else
            {

                if (!txtDebitMoney.Text.Contains("(") && !"0".Equals(txtDebitMoney.Text))
                {
                    if (cbxCustomer.SelectedIndex <= 0)
                    {
                        Error f = new Error("Hãy chọn học viên ghi nợ");
                        f.ShowDialog();
                        f.Dispose();
                        errflg = true;
                    }
                }
                if (errflg == false)
                {
                    int? cusId = null;
                    if (cbxCustomer.SelectedIndex > 0)
                    {
                        cusId = (int)cbxCustomer.SelectedValue;
                    }
                    int proId = (int)cbxProduct.SelectedValue;
                    decimal price = Convert.ToDecimal(txtPrice.Text);
                    decimal quantity = nbquantity.Value;
                    decimal payMoney = 0;
                    if (!string.IsNullOrEmpty(txtPayMoney.Text))
                    {
                        payMoney = Convert.ToDecimal(txtPayMoney.Text);
                    }
                    decimal total = quantity * price;
                    decimal debit = 0;
                    DateTime saleDate = dtSaleDate.Value;
                    if (total > payMoney)
                    {
                        debit = total - payMoney;
                    }
                    else
                    {
                        payMoney = total;
                    }
                    if (sdao.insertSales(proId, cusId, price, quantity, payMoney, debit, saleDate))
                    {
                        Result r = new Result(UserConstant.SAVE_SUCCESSFUL);
                        r.ShowDialog();
                        r.Dispose();                        
                        txtPayMoney.Text = "";
                        cbxCustomer.SelectedIndex = 0;
                        cbxProduct.SelectedIndex = 0;
                        txtPrice.Text = "";
                        txtTotal.Text = ""; 
                        nbquantity.Value = 1;
                        txtDebitMoney.Text = "";
                        loadGrid();
                    }
                    else
                    {
                        Error er = new Error("Lưu thất bại.");
                        er.ShowDialog();
                        er.Dispose();
                    }
                }
            }
        }

        private void btnView_Click(object sender, EventArgs e)
        {
            loadGrid();
        }

        private void dtgCustomers_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            /*if (e.RowIndex >= 0 && e.ColumnIndex == 8)
            {
                int id = int.Parse(dtgCustomers.Rows[e.RowIndex].Cells[7].Value.ToString());
                Confirm con = new Confirm("Bạn có chắc muốn xóa lượt bán này?");
                con.ShowDialog();
                if (con.IsAccept)
                {
                    if (sdao.deleteSale(id))
                    {
                        Result r = new Result("Xóa thành công.");
                        r.ShowDialog();
                        r.Dispose();
                        loadGrid();
                    }
                    else
                    {
                        Error er = new Error("Xóa thất bại.");
                        er.ShowDialog();
                        er.Dispose();
                    }
                }
                con.Dispose();
            }*/
        }

        private void dtgCustomers_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex == 9)
            {
                int id = int.Parse(dtgCustomers.Rows[e.RowIndex].Cells[8].Value.ToString());
                Confirm con = new Confirm("Bạn có chắc muốn xóa lượt bán này?");
                con.ShowDialog();
                if (con.IsAccept)
                {
                    if (sdao.deleteSale(id))
                    {
                        Result r = new Result("Xóa thành công.");
                        r.ShowDialog();
                        r.Dispose();
                        loadGrid();
                    }
                    else
                    {
                        Error er = new Error("Xóa thất bại.");
                        er.ShowDialog();
                        er.Dispose();
                    }
                }
                con.Dispose();
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            txtPayMoney.Text = "0";
            txtPayMoney.Focus();
        }
    }
}
